
puts '[info] begin to aggregate the given score file by last...'

exit 0 if ARGV[0] == nil
workingDir = ARGV[0]
sortedInput = ARGV[1]
aggregatedOutput_last = "#{sortedInput}_last"
aggregatedOutput_max = "#{sortedInput}_max"
aggregatedOutput_sum = "#{sortedInput}_sum"

begin
    sortedInputFile = File.open("#{workingDir}/#{sortedInput}", 'r')
    aggregatedOutputFile_last = File.open("#{workingDir}/#{aggregatedOutput_last}", 'w')
    aggregatedOutputFile_max = File.open("#{workingDir}/#{aggregatedOutput_max}", 'w')
    aggregatedOutputFile_sum = File.open("#{workingDir}/#{aggregatedOutput_sum}", 'w')
    curUid = 0
    curPid = 0
    curRating_last = 0
    curRating_max = 0
    curRating_sum = 0
    curTime_last = ''
    curTime_max = ''
    curTime_sum = ''
    nextUid = 0
    nextPid = 0
    nextRating = 0
    nextTime = ''
    sortedInputFile.each_line { |line|
        arr = line.split("\t")
        nextUid = arr[0].strip.to_i
        nextPid = arr[1].strip.to_i
        nextRating = arr[2].strip.to_i
        nextTime = arr[3].strip
        if nextUid!=0 && nextPid!=0 && nextRating!=0
            if nextUid==curUid && nextPid==curPid
                curRating_last = nextRating
                curTime_last = nextTime
                curRating_max = nextRating if nextRating > curRating_max
                curTime_max = nextTime if nextRating > curRating_max
                curRating_sum = curRating_sum + nextRating
                curTime_sum = nextTime
            else
                aggregatedOutputFile_last.write("#{curUid.to_s}\t#{curPid.to_s}\t#{curRating_last.to_s}\t#{curTime_last}\n") if curUid!=0 && curPid!=0
                aggregatedOutputFile_max.write("#{curUid.to_s}\t#{curPid.to_s}\t#{curRating_max.to_s}\t#{curTime_max}\n") if curUid!=0 && curPid!=0
                aggregatedOutputFile_sum.write("#{curUid.to_s}\t#{curPid.to_s}\t#{curRating_sum.to_s}\t#{curTime_sum}\n") if curUid!=0 && curPid!=0
                curUid = nextUid
                curPid = nextPid
                curRating_last = curRating_max = curRating_sum = nextRating
                curTime_last = curTime_max = curTime_sum = nextTime
            end
        end
    }
    aggregatedOutputFile_last.write("#{curUid.to_s}\t#{curPid.to_s}\t#{curRating_last.to_s}\t#{curTime_last}\n") if curUid!=0 && curPid!=0
    aggregatedOutputFile_max.write("#{curUid.to_s}\t#{curPid.to_s}\t#{curRating_max.to_s}\t#{curTime_max}\n") if curUid!=0 && curPid!=0
    aggregatedOutputFile_sum.write("#{curUid.to_s}\t#{curPid.to_s}\t#{curRating_sum.to_s}\t#{curTime_sum}\n") if curUid!=0 && curPid!=0
ensure
    sortedInputFile.close if sortedInputFile != nil
    aggregatedOutputFile_last.close if aggregatedOutputFile_last != nil
    aggregatedOutputFile_max.close if aggregatedOutputFile_max != nil
    aggregatedOutputFile_sum.close if aggregatedOutputFile_sum != nil
end

puts '[info] Job is done !!!'
